package cj.web.marriageSC.controllers;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.constants.MemuEnum;
import cj.web.login.controllers.BaseController;
import cj.web.marriageSC.dao.SCGoodsDAO;
import cj.web.marriageSC.dao.SCGoodsItemsDAO;
import cj.web.marriageSC.domain.SCGoodsItems;

@Path("/goodsItems")
public class SCGoodsItemsController extends BaseController{

	private static Logger logger = Logger.getLogger(SCGoodsItemsController.class.getName());
	
	@Autowired
	private SCGoodsItemsDAO goodsItemsDao;
	@Autowired
	private SCGoodsDAO goodsDao;

	@Get("show")
	public String show(Model model,@Param("goodsId")int goodsId, HttpServletRequest request)
	{
		model.add("goodsId", goodsId);
		model.add("MemuEnum", MemuEnum.marriagescgoods);
		return "/views/marriageSC/goodsItemsList.vm";
	}
	
	@Post("list")
	public String list(Model model,SCGoodsItems goodsItems)
	{
		List<SCGoodsItems> objs = goodsItemsDao.queryByItemName(goodsItems);
		int size = goodsItemsDao.sizeByItemName(goodsItems);
		
		JSONObject jo = new JSONObject();
		jo.put("data", objs);
		jo.put("draw", goodsItems.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model, @Param("id") int id, HttpServletRequest request)
	{
		SCGoodsItems obj = goodsItemsDao.queryById(id);
		
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.marriagescgoods);
		return "/views/marriageSC/goodsItemsEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,SCGoodsItems goodsItems, HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String acount = returnSessionObj(request).getAccount();
		goodsItems.setUpdateUser(acount);
		
		try {
			goodsItemsDao.update(goodsItems);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		Integer invInt = goodsItems.getInventory();
		if(invInt != null){   
			int inventory = invInt.intValue();
			if(inventory == 0){  //购物车失效
				goodsItemsDao.disableCart(goodsItems.getId().intValue());
			}
		}
		
		updateGoodsPriceRange(goodsItems.getGoodsId().intValue());
		
		return "@" + jo.toString();
	}

	@Get("stick")//置顶
	public String stick(Model model,@Param("id") int id)
	{
		SCGoodsItems obj = goodsItemsDao.queryById(id);
		if(obj != null){
			goodsItemsDao.stick(id);
		}
		
		return "r:show?goodsId=" + obj.getGoodsId();
	}
	
	@Post("upload")
    public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {  
            try {  
            	// 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath_Marriage");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));
                
                ImageUtils.scale3(path+"/"+fileName, path+"/l_"+fileName, 235, 235);//缩率图
                
                ImageUtils.scale2(path+"/l_"+fileName, path+"/ss_"+fileName, 235, 235, true);//缩率图		254*254
                
                jo.put("filePath", rep.get("filepath")+"/ss_"+fileName);
                
            } catch (Exception e) {
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	

	private void updateGoodsPriceRange(int goodsId) {
		List<Map> range = goodsItemsDao.range(goodsId);
		
		double maxOrignPrice = Double.parseDouble(range.get(0).get("maxOrignPrice").toString());
		double minOrignPrice = Double.parseDouble(range.get(0).get("minOrignPrice").toString());
		
		double maxDiscntPrice = Double.parseDouble(range.get(0).get("maxDiscntPrice").toString());
		double minDiscntPrice = Double.parseDouble(range.get(0).get("minDiscntPrice").toString());
		
		String origPriceRange = "";
		if( minOrignPrice == maxOrignPrice ){
			origPriceRange = String.format("%.2f", maxOrignPrice);
		}
		else{
			origPriceRange = String.format("%.2f - %.2f", minOrignPrice, maxOrignPrice);
		}
		
		String discntPriceRange = "";
		if( minDiscntPrice == maxDiscntPrice ){
			discntPriceRange = String.format("%.2f", maxDiscntPrice);
		}
		else{
			discntPriceRange = String.format("%.2f - %.2f", minDiscntPrice, maxDiscntPrice);
		}
		
		goodsDao.updatePriceRange(goodsId, origPriceRange, discntPriceRange);
		
	}
	
}
